	package com.achievo.know.web.component;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.component.impl.FileManagerConfig;
import com.achievo.know.web.util.BaseActionSupport;
import com.redhat.redwork.coc.RedworkAction;

public class ImageUploadAction extends BaseActionSupport implements RedworkAction {

	private File upload;

	private String uploadFileName; // 上传来的文件的名字
	@Autowired
    private FileManagerConfig config;
	
	
	public FileManagerConfig getConfig() {
		return config;
	}

	public void setConfig(FileManagerConfig config) {
		this.config = config;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -5247245013618740662L;

	public void upload() throws IOException {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8"); // 务必，防止返回文件名是乱码
		String realBaseDir = config.getImageUploadStoreDirectory()+"/"+DateFormatUtils.format(new Date(), "yyyyMM")+"/";  
		File baseFile = new File(realBaseDir);  
        if (!baseFile.exists()) {  
            baseFile.mkdirs();  
        }  
        String ext=config.getNameGenerator().getExt(uploadFileName);
        String name=config.getNameGenerator().newFileName();
        upload.renameTo(new File(baseFile,name+"."+ext)); 
        String path =config.getMappingIp()+config.getPathImageUpload()+DateFormatUtils.format(new Date(), "yyyyMM")+"/" + name+"."+ext; 
        String alt_msg = ""; 
        String callback = ServletActionContext.getRequest().getParameter("CKEditorFuncNum");  
        pringWriterToPage("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("  
                + callback  
                + ", '"  
                + path  
                + "' , '"  
                + alt_msg  
                + "');</script>",response);  
		//response.getWriter().write("ok");
		//return null; // 这里不需要页面转向，所以返回空就可以了
	}

	private void pringWriterToPage(String string,HttpServletResponse response) throws IOException {
		response.getWriter().write(string);
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	
	
	
	

}
